/**
 * Created by sun on 2016/8/25.
 */
define(function (require) {
    var app = require('/../js/app');
    require('ui-table');
    require('upload');
    app.useModule("ui.table");
    app.useModule("ngFileUpload");

    var datepicker = require('datepicker');
    var toastr =require('toastr');

    app.controller('reward_ruleCtrl', ['$scope','$http','$filter','Upload',function ($scope, $http,$filter,Upload){
        datepicker($scope);
        $scope.ctrlScope=$scope;

        $scope.isEdit=false;
        $scope.isCheck=false;
        $scope.isCreate=false;

        $scope.inputUser=[];
        $scope.inputInvite=[];
        $scope.fileUser=[];
        $scope.fileInvite=[];
        $scope.searchUser=[];
        $scope.orderParams2=[];

        $scope.select2Options = {
            minimumResultsForSearch: Infinity //不出现搜索框
        };
        $scope.selectOptions = {
            allowClear: false,
            language : 'zh-CN',
        };


        //查询红包明细表
        $scope.checkByName= function (id) {
            $scope.viewRuleModal = !$scope.viewRuleModal;
            $scope.orderParams1.ajaxParam = {ruleId:id};
            $scope.orderParams1.reload();
            $scope.downloadId=id;
        };
        $scope.orderParams1 = {
            url: "/sys/ticketRule/listCouponByRuleId"
        };

        //红包明细表导出
        $scope.download=function(){
            var params={ruleId: $scope.downloadId};
            console.log(params)
            $http.post("/sys/ticketRule/excel/couponByRuleId",params)
                .success(function (data){
                    if(data.result=="success"){
                        window.open(data.file);
                    }else{
                        toastr.error("导出失败");
                    }
                }).error(function(data){
                });
        };

        //项目列表
        $scope.orderParams = {
            url: "/sys/ticketRule/getCouRuleList"
        };

        //搜索
        $scope.search = function() {
            $scope.ctrlScope.itemsearch.beginDateTime=$scope.ctrlScope.itemsearch.beginDateX;
            $scope.ctrlScope.itemsearch.endDateTime=$scope.ctrlScope.itemsearch.endDateX;
            $scope.ctrlScope.itemsearch.beginDateTime=$filter('date')($scope.ctrlScope.itemsearch.beginDateTime,'yyyy-MM-dd');
            $scope.ctrlScope.itemsearch.endDateTime=$filter('date')($scope.ctrlScope.itemsearch.endDateTime,'yyyy-MM-dd');
            $scope.orderParams.ajaxParam=$scope.ctrlScope.itemsearch;
            $scope.orderParams.reload();
        };

        //搜索重置
        $scope.reset=function(){
            $scope.ctrlScope.itemsearch = {};
            $scope.search();
        };

        //增加红包内容
        $scope.num=1;
        $scope.arr=[{index:$scope.num}];

        $scope.add= function () {
            $scope.num++;
            $scope.item={index:$scope.num};
            $scope.arr.push($scope.item)
        };
        //删除红包内容
        $scope.delete= function () {
            $scope.num--;
            $scope.item={index:$scope.num};
            $scope.arr.splice($scope.item.index, 1);
        };

        $scope.modelInit= function () {
            $scope.ctrlScope.rule3={};
            $scope.ctrlScope.rule1={};
            $scope.ctrlScope.rule2={};
            $scope.ctrlScope.rule={};
            $scope.ctrlScope.ruleParent={};
            $scope.ctrlScope.content={};
            $scope.ctrlScope.ruleAnnounce={};
            $scope.ctrlScope.user={};
        };

        //创建
        $scope.addOrderModal=function(){
            $scope.modelInit();
            $scope.itemAddModal = !$scope.itemAddModal;
            $scope.isEdit=false;
            $scope.isCreate=true;

        };


        //编辑
        $scope.openEditModal=function(id){
            $scope.modelInit();
            $scope.isEdit=true;
            $scope.isCheck=false;
            $scope.isCreate=false;
            $scope.itemAddModal = !$scope.itemAddModal;
            $scope.getSingle(id);
            $scope.ruleId=id;
            $scope.id=id;

        };

        //查看红包
        $scope.openViewModal=function(id){
            $scope.isCheck=true;
            $scope.modelInit();
            $scope.orderParams4={};
            $scope.orderParams3={};
            $scope.viewItemModal = !$scope.viewItemModal;
            $scope.getSingle(id);
        };

        $scope.close= function () {
            $scope.viewItemModal = !$scope.viewItemModal;
        };

        //审核
        $scope.openCheckModal= function (id) {
            $scope.ctrlScope.Checkrule={};
            $scope.checkItemModal=!$scope.checkItemModal;
            $scope.checkeRuleId=id;
        };
        //确定审核
        $scope.submit=function(){
            var param= {
                ruleId:$scope.checkeRuleId,
                newStatus:$scope.ctrlScope.Checkrule.status
            };
            console.log(param)
            $http({
                method: 'POST',
                url: "/sys/ticketRule/updateStatus",
                data:param
            }).success(function(data) {
                console.log(data)
                if(data.result=="success"){
                    toastr.success("审核成功");
                    $scope.checkItemModal = !$scope.checkItemModal;
                    $scope.orderParams.reload();
                }else{
                    toastr.error("审核失败");
                }
            }).error(function() {
            });
        };


        //停用
        $scope.openStopModal= function (id) {
            $scope.stopItemModal=!$scope.stopItemModal;
            $scope.stopruleId=id;
            $scope.onOffToStop=false;
        };
        //确定停用

        $scope.confirmStop=function(){
            if($scope.onOffToStop ==true){
                return false;
            }
            $scope.onOffToStop=true;

            $http({
                method: 'POST',
                url: "/sys/ticketRule/updateStatus",
                data:{
                    ruleId:$scope.stopruleId,
                    newStatus:3
                }
            }).success(function(data) {
                console.log(data)
                if(data.result=="success"){
                    toastr.success("停用成功");
                    $scope.stopItemModal = !$scope.stopItemModal;
                    $scope.orderParams.reload();
                }else{
                    toastr.error("停用失败");
                    $scope.onOffToStop=false;
                }
            }).error(function() {
            });
        };
        //取消停用
        $scope.confirmNotStop = function(){
            $scope.stopItemModal = !$scope.stopItemModal;
            $scope.onOffToStop=false;
        };

        //启用
        $scope.openStartModal= function (id) {
            $scope.startItemModal=!$scope.startItemModal;
            $scope.startruleId=id;
            $scope.onOffToStart=false;
        };
        //确定启用
            $scope.confirmStart=function(){
                if($scope.onOffToStart ==true){
                    return false;
                }

                $scope.onOffToStart =true;
                $http({
                    method: 'POST',
                    url: "/sys/ticketRule/updateStatus",
                    data:{
                        ruleId:$scope.startruleId,
                        newStatus:2
                    }
                }).success(function(data) {
                    console.log(data)
                    if(data.result=="success"){
                        toastr.success("启用成功");
                        $scope.startItemModal=!$scope.startItemModal;
                        $scope.orderParams.reload();
                    }else{
                        toastr.error("启用失败");
                        $scope.onOffToStart =false;
                    }
                }).error(function() {
                });
            };

        //取消启用
        $scope.confirmNotStart = function(){
            $scope.startItemModal=!$scope.startItemModal;
            $scope.onOffToStart =false;
        };


        //查询红包规则信息
        $scope.getSingle = function(id){
            $http({
                method: 'POST',
                url: "/sys/ticketRule/getSingle",
                data: {
                    id: id
                }
            }).success(function(data) {
                console.log(data);
                $scope.ctrlScope.rule=data;

                if(data.nid=='send_intime'){
                    $scope.ctrlScope.ruleParent.nid=1
                }else if(data.nid=='bid'){
                    $scope.ctrlScope.ruleParent.nid=10;
                    $scope.ctrlScope.rule1.nid=2
                }else if(data.nid=='invite'){
                    $scope.ctrlScope.ruleParent.nid=10;
                    $scope.ctrlScope.rule1.nid=3
                }else if(data.nid=='realname_invite'){
                    $scope.ctrlScope.ruleParent.nid=11;
                    $scope.ctrlScope.rule2.nid=4
                }else if(data.nid=='first_invest_invite'){
                    $scope.ctrlScope.ruleParent.nid=11;
                    $scope.ctrlScope.rule2.nid=5
                }else if(data.nid=='invest'){
                    $scope.ctrlScope.ruleParent.nid=12;
                    $scope.ctrlScope.rule3.nid=6;
                    $scope.ctrlScope.rule.minimumAmount6=data.minimumAmount;
                }else if(data.nid=='first_invest'){
                    $scope.ctrlScope.ruleParent.nid=12;
                    $scope.ctrlScope.rule3.nid=7;
                    $scope.ctrlScope.rule.minimumAmount7=data.minimumAmount;
                }else if(data.nid=='recharge'){
                    $scope.ctrlScope.ruleParent.nid=8;
                    $scope.ctrlScope.rule.minimumAmount8=data.minimumAmount;
                }else if(data.nid=='lock_bid'){
                    $scope.ctrlScope.ruleParent.nid=9;
                    $scope.ctrlScope.rule.days=data.minimumAmount;
                }else if(data.nid=='total_invest'){
                    $scope.ctrlScope.ruleParent.nid=14;
                    $scope.ctrlScope.rule.minimumAmount9=data.minimumAmount;
                }else if(data.nid=='register'){
                    $scope.ctrlScope.ruleParent.nid=15;
                }

                if(data.whetherSms==0 && data.whetherMail==0 && data.whetherAppPush==0){
                    $scope.ctrlScope.ruleAnnounce.announce=0
                }else{
                    $scope.ctrlScope.ruleAnnounce.announce=1;
                    if(data.whetherSms==1){
                        $scope.ctrlScope.ruleAnnounce.whetherSms=true
                    }else{
                        $scope.ctrlScope.ruleAnnounce.whetherSms=false
                    }

                    if(data.whetherMail==1){
                        $scope.ctrlScope.ruleAnnounce.whetherMail=true
                    }else{
                        $scope.ctrlScope.ruleAnnounce.whetherMail=false
                    }

                    if(data.whetherAppPush==1){
                        $scope.ctrlScope.ruleAnnounce.whetherAppPush=true
                    }else{
                        $scope.ctrlScope.ruleAnnounce.whetherAppPush=false
                    }
                }

                if($scope.isCheck){
                    $scope.getListConfigCoupon = function(){
                        $http({
                            method: 'POST',
                            url: "/sys/ticketRule/listConfigCoupon",
                            data: {
                                ruleId: data.id
                            }
                        }).success(function(data) {
                            console.log(data);
                            $scope.orderParams3=data;
                            $scope.ctrlScope.content.expired=data[0].expiredLife;
                        }).error(function(data) {
                        });
                    };

                    if($scope.ctrlScope.rule.usersType==1) {

                        $scope.getListUser = function () {
                            $http({
                                method: 'POST',
                                url: "/sys/ticketRule/listUserByRuleId",
                                data: {
                                    ruleId: data.id
                                }
                            }).success(function (data) {
                                $scope.orderParams4 = data;
                            }).error(function (data) {
                            });
                        };
                        $scope.getListUser();
                    }

                    $scope.getListConfigCoupon();
                }else{
                    $scope.getListConfigCoupon = function(){
                        $http({
                            method: 'POST',
                            url: "/sys/ticketRule/listConfigCoupon",
                            data: {
                                ruleId: data.id
                            }
                        }).success(function(data) {
                            console.log(data);

                            $scope.dataCoupon=data;

                            $scope.deleteone= function () {

                                $scope.dataCoupon.pop();

                            };

                            if($scope.ctrlScope.rule.ticketType==1){
                                $scope.addone= function () {
                                    $scope.dataCoupon.push({
                                        expiredLife:'',
                                        scope:'',
                                        amount:'',
                                        requireAmount:'',
                                        type:1,
                                        status:1
                                    });
                                };
                            }else if($scope.ctrlScope.rule.ticketType==2){
                                $scope.addone= function () {
                                    $scope.dataCoupon.push({
                                        expiredLife:'',
                                        scope:'',
                                        usefulLife:'',
                                        requireAmount:'',
                                        rate:'',
                                        type:2,
                                        status:1
                                    });

                                };
                            }




                        }).error(function(data) {
                        });
                    };

                    if($scope.ctrlScope.rule.usersType==1) {
                        $scope.getListUser = function () {
                            $http({
                                method: 'POST',
                                url: "/sys/ticketRule/listUserByRuleId",
                                data: {
                                    ruleId: data.id
                                }
                            }).success(function (data) {
                                $scope.orderParams2 = data;
                            }).error(function (data) {
                            });
                        };
                        $scope.getListUser();
                    }
                    $scope.getListConfigCoupon();

                }


            }).error(function(data) {
            });
        };



        //输入指定用户获取用户列表
        $scope.listInputUser= function () {
            console.log($scope.ctrlScope.userNames)
            $http({
                method: 'POST',
                url:"/sys/ticketRule/listInputUser",
                data:{userNames:$scope.ctrlScope.userNames},
            }).success(function (data){
                console.log(data);
                $scope.inputUser=data;
                $scope.orderParams2.push.apply($scope.orderParams2,$scope.inputUser);
            }).error(function(data){

            });
        };


        //输入邀请人获取用户列表
        $scope.listInputInvite= function () {
            console.log($scope.ctrlScope.inviteUserNames)
            $http({
                method: 'POST',
                url:"/sys/ticketRule/listInputInvite",
                data:{inviteUserNames:$scope.ctrlScope.inviteUserNames},
            }).success(function (data){
                console.log(data)
                $scope.inputInvite=data;
                $scope.orderParams2.push.apply($scope.orderParams2,$scope.inputInvite);
            }).error(function(data){

            });
        };


        //指定用户搜索
        $scope.userSearch= function () {
            $scope.ctrlScope.user.beginInvestTime=$scope.ctrlScope.user.beginInvestTimex;
            $scope.ctrlScope.user.endInvestTime=$scope.ctrlScope.user.endInvestTimex;
            $scope.ctrlScope.user.beginInvestTime=$filter('date')($scope.ctrlScope.user.beginInvestTime,'yyyy-MM-dd');
            $scope.ctrlScope.user.endInvestTime=$filter('date')($scope.ctrlScope.user.endInvestTime,'yyyy-MM-dd');
            $http({
                method: 'POST',
                url:"/sys/ticketRule/listUser",
                data:$scope.ctrlScope.user
            }).success(function (data){
                $scope.searchUser=data;
                $scope.orderParams2.push.apply($scope.orderParams2,$scope.searchUser);
            }).error(function(data){

            });
        };

        //上传指定用户
        $scope.upload = function (file) {
            Upload.upload({
                url: "/sys/ticketRule/listUploadUser",
                data: {file: file, 'username': $scope.username}
            }).then(function (resp) {
                if(resp.config.data.file) {
                    console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
                    $scope.fileUser=resp.data;
                    $scope.orderParams2.push.apply($scope.orderParams2,$scope.fileUser);
                }
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                if(evt.config.data.file) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                }
            });
        };

        //根据邀请人获取用户列表
        $scope.upload1 = function (file) {
            Upload.upload({
                url: "/sys/ticketRule/listInviteUser",
                data: {file: file, 'username': $scope.username}
            }).then(function (resp) {
                if(resp.config.data.file){
                    console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
                    $scope.fileInvite=resp.data;
                    $scope.orderParams2.push.apply($scope.orderParams2,$scope.fileInvite);

                }
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                if(evt.config.data.file){
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                }

            });
        };

        //删除列表项
        $scope.deleteUserModal= function (item) {
            $scope.orderParams2.splice(item, 1);
        };

        //创建 / 编辑 提交
        $scope.submitForm = function(isValid) {
            if (!isValid) {
                toastr.error("信息填写有误");
            }
            var json={};
            json.ticketRule={
                name:$scope.ctrlScope.rule.name,
                beginTime:$filter('date')($scope.ctrlScope.rule.beginTime,'yyyy-MM-dd'),
                endTime:$filter('date')($scope.ctrlScope.rule.endTime,'yyyy-MM-dd'),
                nid:'',
                minimumAmount:null,
                whetherSms:0,
                whetherMail:0,
                whetherAppPush:0,
                usersType:$scope.ctrlScope.rule.usersType,
                limitType:$scope.ctrlScope.rule.limitType,
                totalLimit:$scope.ctrlScope.rule.totalLimit,
                totalCount:$scope.ctrlScope.rule.totalCount,
                jumpPage:$scope.ctrlScope.rule.jumpPage,
                ticketType:$scope.ctrlScope.rule.ticketType,
                noticeContent:$scope.ctrlScope.rule.noticeContent
            };
            if(!$scope.isCreate){
                json.ticketRule.id=$scope.id
            }

            if($scope.ctrlScope.ruleParent.nid==1){
                json.ticketRule.nid='send_intime';
            }else if($scope.ctrlScope.ruleParent.nid==10){
                if($scope.ctrlScope.rule1.nid==2){
                    json.ticketRule.nid='bid';
                }else if($scope.ctrlScope.rule1.nid==3){
                    json.ticketRule.nid='invite';
                }
            }else if($scope.ctrlScope.ruleParent.nid==11){
                if($scope.ctrlScope.rule2.nid==4){
                    json.ticketRule.nid='realname_invite';
                }else if($scope.ctrlScope.rule2.nid==5){
                    json.ticketRule.nid='first_invest_invite';
                }
            }else if($scope.ctrlScope.ruleParent.nid==12){
                if($scope.ctrlScope.rule3.nid==6){
                    json.ticketRule.nid='invest';

                    json.ticketRule.minimumAmount=$scope.ctrlScope.rule.minimumAmount6;
                }else if($scope.ctrlScope.rule3.nid==7){

                    json.ticketRule.nid='first_invest';
                    json.ticketRule.minimumAmount=$scope.ctrlScope.rule.minimumAmount7;
                }
            }else if($scope.ctrlScope.ruleParent.nid==8){
                json.ticketRule.nid='recharge';
                json.ticketRule.minimumAmount=$scope.ctrlScope.rule.minimumAmount8;
            }else if($scope.ctrlScope.ruleParent.nid==9){
                json.ticketRule.nid='lock_bid';
                json.ticketRule.minimumAmount=$scope.ctrlScope.rule.days;
            }else if($scope.ctrlScope.ruleParent.nid==13){
                json.ticketRule.redeemCode=$scope.ctrlScope.rule.redeemCode;
            }else if($scope.ctrlScope.ruleParent.nid==14){
                json.ticketRule.nid='total_invest';
                json.ticketRule.minimumAmount=$scope.ctrlScope.rule.minimumAmount9;
            }else if($scope.ctrlScope.ruleParent.nid==15){
                json.ticketRule.nid='register';
            }

            if($scope.ctrlScope.ruleAnnounce.announce==1){
                if($scope.ctrlScope.ruleAnnounce.whetherSms==true){
                    json.ticketRule.whetherSms=1
                }else{
                    json.ticketRule.whetherSms=0
                }
                if($scope.ctrlScope.ruleAnnounce.whetherMail==true){
                    json.ticketRule.whetherMail=1
                }else{
                    json.ticketRule.whetherMail=0
                }
                if($scope.ctrlScope.ruleAnnounce.whetherAppPush==true){
                    json.ticketRule.whetherAppPush=1
                }else{
                    json.ticketRule.whetherAppPush=0
                }
            }
            json.list=[];
            if($scope.ctrlScope.rule.ticketType==1){
                if($scope.isCreate){

                    var datajson=$scope.ctrlScope.content;

                    for(var i=0;i<$scope.num;i++){
                        json.list.push({
                            expiredLife:datajson.expiredLife[i],
                            scope:datajson.scope[i],
                            amount:datajson.amount[i],
                            requireAmount:datajson.requireAmount[i],
                            type:1,

                        })
                    }
                }else{
                    json.list=$scope.dataCoupon;
                    console.log($scope.dataCoupon)
                }
            }else if($scope.ctrlScope.rule.ticketType==2){
                if($scope.isCreate){

                    var datajson=$scope.ctrlScope.content;

                    for(var i=0;i<$scope.num;i++){
                        json.list.push({
                            expiredLife:datajson.expiredLife[i],
                            scope:datajson.scope[i],
                            usefulLife:datajson.usefulLife[i],
                            requireAmount:datajson.requireAmount[i],
                            rate:datajson.rate[i],
                            type:2
                        })
                    }
                }else{
                    json.list=$scope.dataCoupon;
                    console.log($scope.dataCoupon)
                }
            }else if($scope.ctrlScope.rule.ticketType==3){
                if($scope.isCreate){
                    json.list.push({
                        expiredLife:$scope.ctrlScope.content.expired,
                        type:3
                    });
                }else{
                    json.list=$scope.dataCoupon;
                    console.log(json.list)
                }


            }

            console.log(json.list);
            json.userIdLink='';
            if($scope.orderParams2){
                for(var j=0;j<$scope.orderParams2.length;j++){
                    json.userIdLink+=$scope.orderParams2[j].id+','
                }
            }
            console.log(json.ticketRule);

            var url='';
            if($scope.isEdit){
                url="/sys/ticketRule/updateRule";
            }else{

                url="/sys/ticketRule/addRule";
            }

            $http.post(url,json.ticketRule)
                .success(function(data) {
                    if(data.result=="success"){


                        if($scope.isCreate){
                            for(var i=0;i<json.list.length;i++){
                                var param = json.list[i];
                                param.ruleId=data.ruleId;

                                $http.post("/sys/ticketRule/addConfigTicket",param)
                                    .success(function(data) {
                                        if(data.result=="success"){

                                        }else{
                                            toastr.error("红包内容提交失败");
                                        }
                                    }).error(function() {
                                    });
                            }

                            var userParam = {
                                userIdLink:json.userIdLink,
                                ruleId:data.ruleId
                            };

                            if($scope.ctrlScope.rule.usersType==1) {

                                $http.post("/sys/ticketRule/addUser", userParam)
                                    .success(function (data) {
                                        if (data.result == "success") {


                                        } else {
                                            toastr.error("用户筛选提交失败");
                                        }
                                    }).error(function () {
                                    });
                            }

                        }else{

                            json.listUpdate=[];
                            json.listadd=[];


                            for(var i=0;i<json.list.length;i++) {
                                if (json.list[i].id) {
                                    json.listUpdate.push(json.list[i]);

                                } else {
                                    json.listadd.push(json.list[i]);

                                }
                            }


                           for(var j=0;j<json.listUpdate.length;j++) {
                               var paramUpdate = json.listUpdate[j];
                           }

                            for(var l=0;l<json.listadd.length;l++) {
                                var paramadd = json.listadd[l];
                                paramadd.ruleId=$scope.ruleId

                            }


                            if(paramUpdate){
                               console.log(paramUpdate)

                                    $http.post("/sys/ticketRule/updateConfigTicket",paramUpdate)
                                        .success(function(data) {
                                            if(data.result=="success"){

                                            }else{
                                                toastr.error("红包内容提交失败");
                                            }
                                        }).error(function() {
                                        });





                            }
                            if(paramadd) {

                                $http.post("/sys/ticketRule/addConfigTicket", paramadd)
                                    .success(function (data) {
                                        if (data.result == "success") {

                                        } else {
                                            toastr.error("红包内容提交失败");
                                        }
                                    }).error(function () {
                                    });
                            }
                                }


                        toastr.success("提交成功");
                        $scope.itemAddModal = !$scope.itemAddModal;
                        $scope.orderParams.reload();

                    }else{
                        toastr.error("红包规则提交失败");
                    }
                }).error(function() {
                });
        };







    }]);


});